package com.takepoints.mobile;

import java.util.ArrayList;
import java.util.List;

import com.takepoints.android.bo.EventNews;
import com.takepoints.android.db.EventNewsAdapter;
import com.takepoints.android.services.PublicServices;
import com.takepoints.android.util.AnimationUtil;
import com.takepoints.android.util.DownloadImageTask;
import com.takepoints.android.util.ImageUtil;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class TPEventNews extends BaseActivity {
	
	private ListView lstEvents = null;
	private EventListAdapter eventAdapter = null;
	private TextView txtHeader = null;
	private Button btnLoadMore = null;
	private RelativeLayout loadingPanel = null;
	
	private EventNewsAdapter eventDbApt = null;
	
	private final String IMG_URL = "https://www.takepoints.com/public/uploads/tmobile/";
	
	public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.eventnews);
        
        txtHeader = (TextView)findViewById(R.id.txtHeader);
        txtHeader.setText("ข่าวสารและกิจกรรม");
        manageMenu(0);
        
		btnLoadMore = (Button)findViewById(R.id.btnLoadMore);
        btnLoadMore.setOnClickListener(new View.OnClickListener(){
			 public void onClick(View view) {
				 processEvents();
			 }
        });
        eventDbApt = new EventNewsAdapter(this);
        eventDbApt.open();
        
        loadingPanel = (RelativeLayout)findViewById(R.id.loadingPanel);
        
        lstEvents = (ListView)findViewById(R.id.lstEvents);
        lstEvents.setLayoutAnimation(new AnimationUtil().getSlideDownAnimateCtrl());
        
        eventAdapter = new EventListAdapter(new ArrayList<EventNews>());
        lstEvents.setAdapter(eventAdapter);
        
        List<EventNews> events = eventDbApt.getEventNewsList(null);
    	int n = (events==null)?0:events.size();
    	for(int i=0; i<n; i++){
    		EventNews event = events.get(i);
			eventAdapter.add(event);
    	}
        processEvents();
	}
	
	private void processEvents(){
		String lastDate = eventDbApt.getMaxEventDate();
		new FetchLastEvents().execute(lastDate);
	}
	
	@Override
    protected void onResume(){
    	super.onResume();
	}
	
	@Override
    protected void onPause(){
    	super.onPause();
	}
	
	@Override
    protected void onDestroy(){
		eventDbApt.close();
    	super.onDestroy();
    }
	
	private class EventListAdapter extends BaseAdapter {
		private List<EventNews> eventList;
		private LayoutInflater mInflater;

		public EventListAdapter(List<EventNews> eventList){
			mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.eventList = eventList;
		}
		
		public void addTop(EventNews event){
			eventList.add(0, event);
			notifyDataSetChanged();
		}
		public void add(EventNews event){
			eventList.add(event);
			notifyDataSetChanged();
		}
		
		public void removeAll(){
			eventList.clear();
			notifyDataSetChanged();
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			final View rowView = (convertView!=null)?convertView:mInflater.inflate(R.layout.eventrow, null);
			final EventNews event = eventList.get(position);
			if(event != null){
				ImageView imgTitle = (ImageView)rowView.findViewById(R.id.imgTitle);
				if(imgTitle != null){
					/*Bitmap bitmap = BitmapFactory.decodeFile(IMG_CACHE_PATH + event.getImgTitle());
					if(bitmap != null){
						//imgTitle.setImageBitmap(bitmap);
						imgTitle.setImageBitmap(ImageUtil.getRoundedBitmap(bitmap, 5, Color.GRAY));
					} else{
						imgTitle.setTag(IMG_URL + event.getImgTitle());
						new DownloadImageTask().execute(imgTitle);
					}*/
					if(event.getImgTitle() != null){
						imgTitle.setImageResource(R.drawable.iconapp);
					} else{
						imgTitle.setImageResource(R.drawable.iconapp);
					}
				}
				
				//TextView txtPoints = (TextView)rowView.findViewById(R.id.txtPoints);
				//txtPoints.setText(event.getEventPoint());
				
				LinearLayout lnrDetail = (LinearLayout)rowView.findViewById(R.id.lnrDetail);
				lnrDetail.removeAllViews();
				if(lnrDetail != null){
					TextView txtTitle = new TextView(lnrDetail.getContext());
					txtTitle.setText(event.getTitle());
					txtTitle.setTextSize(12);
					txtTitle.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
					txtTitle.setTextColor(Color.parseColor("#78a023"));
					txtTitle.setHeight(LayoutParams.WRAP_CONTENT);
					txtTitle.setPadding(10, 1, 1, 1);
					txtTitle.setSingleLine(false);
					lnrDetail.addView(txtTitle);
					
					TextView txt1 = new TextView(lnrDetail.getContext());
					txt1.setText(event.getDetail());
					txt1.setTextSize(11);
					txt1.setTextColor(Color.parseColor("#404a4a"));
        	        txt1.setHeight(LayoutParams.WRAP_CONTENT);
					txt1.setPadding(9, 1, 1, 1);
					txt1.setSingleLine(false);
					lnrDetail.addView(txt1);
				}
				
				rowView.setOnClickListener(new View.OnClickListener(){
					 public void onClick(View view) {
						 alert(event.getDetail());
					 }
				});
				rowView.setOnTouchListener(new View.OnTouchListener(){
					 public boolean onTouch(View v, MotionEvent event){
						 int action = event.getAction();
						 switch(action){
						 	case MotionEvent.ACTION_DOWN:
						 		rowView.setBackgroundColor(Color.LTGRAY);
						 		break;
						 	case MotionEvent.ACTION_UP:
						 		rowView.setBackgroundResource(R.drawable.bg_item);
						 		break;
						 	case MotionEvent.ACTION_MOVE:
						 		rowView.setBackgroundResource(R.drawable.bg_item);
						 		break;
						 	case MotionEvent.ACTION_CANCEL:
						 		rowView.setBackgroundResource(R.drawable.bg_item);
						 		break;
						 	default:
						 		break;
						 }
						 return false;
					}
				});
			}
			return rowView;
		}

		@Override
		public int getCount() {
			return eventList.size();
		}

		@Override
		public Object getItem(int position) {
			return eventList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return eventList.get(position).hashCode();
		}
	}
	
	class FetchLastEvents extends AsyncTask<String, Void, List<EventNews>>{
		
        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            loadingPanel.setVisibility(View.VISIBLE);
        }
        
        @Override
        protected List<EventNews> doInBackground(String... params){
        	String lastDateTime = params[0];
        	return PublicServices.getLastEvents(lastDateTime);
        }
        
        @Override
        protected void onPostExecute(List<EventNews> result){
        	int rows = (result==null)?0:result.size();
        	for(int i=0; i<rows; i++){
        		EventNews event = result.get(i);
        		if(event != null){
	        		eventDbApt.add(event);
	        		eventAdapter.addTop(event);
        		}
        	}
        	loadingPanel.setVisibility(View.GONE);
        }
    }
	
}
